package cn.donzell.app.utils;

import cn.donzell.app.model.Address;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//省市区常量集
public class ConstAreaUtil {

    public static final List<Address> addressList = new ArrayList<>();//省份信息

    static {
        ObjectMapper objectMapper = new ObjectMapper();
        File file = new File("config/areaCode.json");
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readValue(file, JsonNode.class);
        } catch (IOException e) {
            throw new RuntimeException("json文件读取异常");
        }
        for (JsonNode citys : jsonNode.get("province")) {
            Address address = new Address(citys.get("name").asText(), citys.get("zip").asInt());
            //市的信息
            List<Address> subArea = new ArrayList<>();
            for (JsonNode jcityNode : citys.get("city")) {
                Address adressCity = new Address(jcityNode.get("name").asText(), jcityNode.get("zip").asInt());
                List<Address> areaList = new ArrayList<>();
                if (jcityNode.get("county") == null) {
                    String areaName = jcityNode.get("name").asText();
                    int zip = jcityNode.get("zip").asInt();
                    areaList.add(new Address(areaName, zip));
                    adressCity.setChildren(areaList);
                    subArea.add(adressCity);
                    continue;
                }
                for (JsonNode areaNode : jcityNode.get("county")) {
                    String areaName = areaNode.get("name").asText();
                    int zip = areaNode.get("zip").asInt();
                    //区县的信息
                    areaList.add(new Address(areaName, zip));
                }
                adressCity.setChildren(areaList);
                subArea.add(adressCity);
            }
            address.setChildren(subArea);
            addressList.add(address);
        }
    }
}
